var express = require('express');
var router = express.Router();
var model = require('../models/index'),
    MUser = model.MUser,
    PayOff = model.PayOff;
var model = require('../models/qrcode'),
    QRcode=model.QRcode;
var _ = require('underscore');
var async = require('async');
require('date-utils');
var Page = require('../utils/Page');
var settings = require('../config');
var crypto = require('crypto');

/* GET home page. */
router.get('/login', function (req, res) {
    if (req.session.user) {
        getPayOffPages(1, res);
    } else {
        res.render('login', { title: '登陆页', message: ""});
    }
});
router.post('/login', function (req, res) {
    var username = req.body.username;
    var md5 = crypto.createHash('md5');
    md5.update(req.body.user_passwd);
    var passwd = md5.digest('hex');
    new MUser().findMUser({
            user_name: username
        }, function (err, user) {
            if (user) {
                if (user.user_passwd == passwd) {
                    req.session.user = user;
                    if(user.user_type==0){
                        getPayOffPages(1, res);
                    }else if(user.user_type==1){
                        getMusers(1, res);
                    }else{
                        res.render('login', { title: '登陆页', message: "用户名或密码错误!" });
                    }

                } else {
                    res.render('login', { title: '登陆页', message: "用户名或密码错误!" });
                }
            }
        }
    )
});
router.get('/index/page', function (req, res) {
    var current_page = req.query.page;
    getPayOffPages(current_page, res);
})
router.get('/index/userPage', function (req, res) {
    var current_page = req.query.page;
    getMusers(current_page, res);
})
router.post('/index/payed', function (req, res) {
    var pid = req.body.id;
    new PayOff().updatePayOff(pid, function (err) {
        if (err) {
            res.json({staus: "fail"});
        } else {
            res.json({staus: "success"});
        }
    })
})
router.get('/logout', function (req, res) {
    req.session.user = null;
    res.redirect('/login');
})
router.get('/reset', function (req, res) {
    res.render('reset', {
        tilte: '密码重置'
    })
})

//二维码管理
router.get('/qrcode',function(req,res){
    var current_page = req.query.page;
    getCodeOffPages(current_page, res);
});
router.get('/createQRcode',function(req,res){
    var err=req.query.err;
    res.render('createQRcode',{err:err});
});
router.post('/createQRcode',function(req,res){
    var codename=req.body.codename;
    var times = new Date().getTime();
    var timestamp=times+"a1a1a1a1a1a1a1a1a1a1a1";
    new QRcode().findAllByName(codename,function(err,datas){
        if(err){console.log("findAllByName err")}
        if(datas.length==0){
            var qr = new QRcode({
                codename:codename,
                codeid: timestamp
            });
            qr.save(function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            return res.redirect('/qrcode?page=1');
        }else{
            return res.redirect('/createQRcode?err=1');
        }
    });

});

router.get('/removecode',function(req,res){
    var codeid=req.query.codeid;
    console.log(codeid)
    new QRcode().removecode(codeid,function(err){
        if(err){
            console.log(err);
        }else{
            return res.redirect('/qrcode?page=1');
        }
    });
});

router.post('/reset/submit', function (req, res) {
    var newpasswd = req.body.newpasswd;
    var md5 = crypto.createHash('md5');
    md5.update(req.body.oldpasswd);
    var oldpasswd = md5.digest('hex');
    var renewpasswd = req.body.renewpasswd;
    //判断原始密码是否输入正确
    if (oldpasswd == req.session.user.user_passwd) {
        if (newpasswd == renewpasswd) {
            req.session.user = null;
            var md5 = crypto.createHash('md5');
            md5.update(newpasswd);
            newpasswd = md5.digest('hex');
            new MUser().updatMUser(newpasswd, function (err) {
                if (err) {
                    console.log("---------------------------------------", err);
                    res.json({message: '系统出错啦', status: "fail"});
                } else {
                    res.json({message: '密码更新成功!!', status: "success"});
                }
            })
        } else {
            res.json({message: '两次输入的密码不一致', status: "fail"})
        }
    } else {
        res.json({message: '原始密码错误！', status: "fail"})
    }
})

function getPayOffPages(currentpage, res) {
    async.waterfall([function (cb) {
        new PayOff().getCount(function (err, count) {
            cb(err, count);
        })
    }], function (err, count) {
        new PayOff().findPayoff(currentpage, function (err, result) {
            var rs = {};
            var page = new Page();
            page.total_row = count;
            if (result.length != 0)page.total_page = Math.ceil(count / settings.pre_page_row);
            page.current_page = currentpage;
            rs.page = page;
            if (err) {
                res.render('error', {
                    message: '结算单管理',
                    error: err
                });
            } else {
                var payoffs = new Array();
                for (var i = 0; i < result.length; i++) {
                    var payoff = _.clone(result[i]);
                    payoff.payoff_date = payoff.payoff_date.toFormat('YYYY-MM-DD');
                    payoffs.push(payoff);
                }
                rs.payoffs = payoffs;
                res.render('index', {
                    title: '结算单管理',
                    result: rs
                });
            }
        })
    })

}

function getMusers(currentpage, res) {
    async.waterfall([function (cb) {
        new MUser().getCount(function (err, count) {
            cb(err, count);
        })
    }], function (err, count) {
        new MUser().getUsers(currentpage, function (err, result) {
            var rs = {};
            var page = new Page();
            page.total_row = count;
            if (result.length != 0)page.total_page = Math.ceil(count / settings.pre_page_row);
            page.current_page = currentpage;
            rs.page = page;
            if (err) {
                res.render('error', {
                    message: '奇妙在线定制系统',
                    error: err
                });
            } else {
                var musers = new Array();
                for (var i = 0; i < result.length; i++) {
                    var muser = _.clone(result[i]);
                    muser.createtime = muser.createtime.toFormat('YYYY-MM-DD');
                    musers.push(muser);
                }
                rs.musers = musers;
                res.render('index1', {
                    title: '奇妙在线定制系统',
                    result: rs
                });
            }
        })
    })

}

function getCodeOffPages(currentpage, res) {
    async.waterfall([function (cb) {
        new QRcode().getCount(function (err, count) {
            cb(err, count);
        })
    }], function (err, count) {
        new QRcode().findQRcode(currentpage, function (err, result) {
            var rs = {};
            var page = new Page();
            page.total_row = count;
            if (result.length != 0)page.total_page = Math.ceil(count / settings.pre_page_row1);
            page.current_page = currentpage;
            rs.page = page;
            if (err) {
                res.render('error', {
                    message: '网络错误',
                    error: err
                });
            } else {
                var codes = new Array();
                for (var i = 0; i < result.length; i++) {
                    var code = _.clone(result[i]);
                    codes.push(code);
                }
                rs.codes = codes;
                res.render('qrcode', {
                    title: '结算单管理',
                    datas: rs
                });
            }
        })
    })

}

module.exports = router;
